<template>
    <el-dialog title="考试链接" :visible.sync="dialogVisible" width="50%">
        <div>
            <el-input placeholder="请输入内容" v-model="url" :disabled="true" class="input-with-select">
                <el-button slot="append" icon="el-icon-search" @click="copy"></el-button>
            </el-input>
        </div>
        <div>
            <img v-if="url" :src="qrCodeDataUrl" alt="QR Code" />
            <el-button @click="downloadQRCode">下载二维码</el-button>
        </div>
    </el-dialog>
</template>

<script>
import QRCode from 'qrcode';
export default {
    name: "train-link",
    data() {
        return {
            dialogVisible: false,
            url: '',
            qrCodeDataUrl: ''
        };
    },
    mounted() {
    },
    methods: {
        show(item) {
            this.url = "http://localhost:8523/online/studentTrain/paperLink?examinationPlanId=" + item.examinationPlanId
            this.dialogVisible = true;
            this.generateQRCode();
        },
        copy() {
            navigator.clipboard.writeText(this.url).then(() => {
                this.$message.success('链接已复制到剪贴板');
            }).catch(err => {
                this.$message.error('复制失败，请手动复制');
                console.error('复制失败:', err);
            });
        },
        async generateQRCode() {
            QRCode.toDataURL(
                this.url, {
                color: {
                    dark: "#000000",
                    light: "#ffffff",
                },
                width: 300,
                height: 300
            }
            ).then((url) => {
                // 获取到url后即可在页面使用--二维码图片
                console.log('url', url)
                this.qrCodeDataUrl = url
            })
        },
        downloadQRCode() {
            if (this.qrCodeDataUrl) {
                const link = document.createElement('a');
                link.href = this.qrCodeDataUrl;
                link.download = 'QRCode.png'; // 下载的文件名
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            } else {
                this.$message.warning('二维码未生成');
            }
        }

    }
};
</script>
